import requests
import re

def get_exchange_rate():
    """
    获取实时汇率（CNY/USD）。
    """
    url = "https://api.exchangerate-api.com/v4/latest/USD"
    try:
        response = requests.get(url)
        data = response.json()
        return data["rates"].get("CNY", 7.1)  # 默认 7.1 作为备用汇率
    except Exception:
        return 7.1

def recognize_currency(currency_input):
    """
    识别用户输入的货币类型，支持多种写法。
    """
    currency_map = {
        "人民币": "CNY", "元": "CNY", "CNY": "CNY", "YUAN": "CNY", "yuan": "CNY", "rmb": "CNY", "RMB": "CNY", "￥": "CNY",
        "美元": "USD", "USD": "USD", "usd": "USD", "dollar": "USD", "DOLLAR": "USD", "$": "USD"
    }
    return currency_map.get(currency_input.strip().lower(), None)

def extract_amount_currency(user_input):
    """
    从输入字符串中提取金额和货币类型。
    """
    match = re.match(r"(\d+\.?\d*)(\D+)", user_input.strip())
    if match:
        amount = float(match.group(1))
        currency = recognize_currency(match.group(2))
        return amount, currency
    return None, None

def convert_currency(amount, from_currency, exchange_rate):
    """
    根据实时汇率进行转换。
    """
    if from_currency == "CNY":
        return round(amount / exchange_rate, 2), "USD"
    elif from_currency == "USD":
        return round(amount * exchange_rate, 2), "CNY"
    else:
        return None, None

def main():
    """
    主程序，循环运行，直到用户输入 "OK" 退出。
    """
    exchange_rate = get_exchange_rate()  # 获取最新汇率
    print(f"当前汇率：1 USD = {exchange_rate} CNY")
    
    while True:
        user_input = input("请输入金额和货币（如 100人民币 或 50USD），输入 'OK' 退出: ").strip()
        
        if user_input.upper() == "OK":
            print("感谢您的使用！")
            break
        
        try:
            amount, from_currency = extract_amount_currency(user_input)
            
            if amount is None or from_currency is None:
                raise ValueError("无法解析输入，请使用正确格式（如 100人民币 或 50USD）")
            
            converted_amount, to_currency = convert_currency(amount, from_currency, exchange_rate)
            print(f"转换结果: {converted_amount} {to_currency}")
        
        except ValueError as e:
            print(f"输入错误: {e}")

if __name__ == "__main__":
    main()
